package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.bean.Price;
import com.aoxon.cargo.cache.FileManager;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.cache.keyCache;
import com.aoxon.cargo.component.ClassifyDialog;
import com.aoxon.cargo.component.MyAlertDialog;
import com.aoxon.cargo.component.MyCallBack;
import com.aoxon.cargo.component.MyListDialog;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.component.MySquarePicture;
import com.aoxon.cargo.component.MyTextWatcher;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.AddGoodsService;
import com.aoxon.cargo.service.FileUpLoadService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RevampGoodsService;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyReturnState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ImageUtil;
import com.aoxon.cargo.util.ToastUtil;

/**
 * 添加新商品的界面
 * 
 * @author ZZJ
 * 
 */
public class SupInputGoodsInfoActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	public static boolean TO_ADD_GOODS = true; // 标志是否是进行添加物品的处理

	private EditText etGoodsName;
	private EditText etGoodsNumber;
	private EditText etGoodsPrice;
	// private EditText etGoodsDescribe;

	private ImageView ivReturnButton;
	private ImageView ivCommitButton;
	private ImageView ivAddPictureButton;
	// private ImageView ivAddPriceButton;

	private TextView tvTitle;
	private TextView tvClassOne;
	private TextView tvClassTwo;

	private LinearLayout llHolder;
	private LinearLayout llGoodsPicture;
	// private LinearLayout llGoodsPrice;

	private MyAlertDialog myAlertDialog;
	private MyProgressDialog myProgressDialog;
	private MyListDialog myListDialog;
	private MySquarePicture mySquarePicture;
	private MyTextWatcher myTextWatcher;
	private ClassifyDialog showClassifyDialog;
	// private SupPriceControl supPriceControl;

	private GsonBean goodsGsonBean;
	private Cloth myCloth = new Cloth();

	private FileManager imageManager = new FileManager();
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private FileUpLoadService fileUploadService = (FileUpLoadService) MyServiceFactory
			.getInstance(MyServiceFactory.FILE_UPLOAD);
	private RevampGoodsService revampGoodsService = (RevampGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.REVAMP_GOODS);
	private AddGoodsService addGoodsService = (AddGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.ADD_GOODS);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();

	}

	/**
	 * 自定义方法
	 * ******************************************************************************************************************************************/

	private void setup() {
		setContentView(R.layout.sup_input_goods_information);
		if(SupCache.pictureList == null){
			SupCache.pictureList = new ArrayList<Picture>();
		}
		// etGoodsDescribe = (EditText)
		// findViewById(R.id.etAddNewGoodsDescribe);
		etGoodsName = (EditText) findViewById(R.id.etAddNewGoodsName);
		etGoodsNumber = (EditText) findViewById(R.id.etAddNewGoodsNumber);
		etGoodsPrice = (EditText) findViewById(R.id.etAddNewGoodsPrice);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivCommitButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		ivAddPictureButton = (ImageView) findViewById(R.id.ivAddNewGoodsPictureButton);
		// ivAddPriceButton = (ImageView)
		// findViewById(R.id.ivAddNewGoodsPriceButton);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		tvClassOne = (TextView) findViewById(R.id.tvAddNewGoodsClassifyOne);
		tvClassTwo = (TextView) findViewById(R.id.tvAddNewGoodsClassifyTwo);

		llHolder = (LinearLayout) etGoodsName.getParent().getParent();
		// llGoodsPrice = (LinearLayout) findViewById(R.id.llAddNewGoodsPrice);
		llGoodsPicture = (LinearLayout) findViewById(R.id.llAddNewGoodsPicture);

		myAlertDialog = new MyAlertDialog(this);
		myListDialog = new MyListDialog(this);
		myProgressDialog = new MyProgressDialog(this);
		myProgressDialog = new MyProgressDialog(this);
		myTextWatcher = new MyTextWatcher(new textWhatcherBack());
		mySquarePicture = new MySquarePicture(this, llGoodsPicture, true);
		// supPriceControl = new SupPriceControl(SupInputGoodsInfoActivity.this,
		// llGoodsPrice, ivCommitButton);
		showClassifyDialog = new ClassifyDialog(this,
				normalDataLoader.getHandler(), tvClassOne, tvClassTwo);

		normalDataLoader.setOnloadDataListener(this);

		ivCommitButton.setImageResource(R.drawable.button_public_commit);
		ivCommitButton.setEnabled(false);

		ivReturnButton.setOnClickListener(myClickListener);
		ivCommitButton.setOnClickListener(myClickListener);
		ivAddPictureButton.setOnClickListener(myClickListener);
		// ivAddPriceButton.setOnClickListener(myClickListener);
		tvClassOne.setOnClickListener(myClickListener);
		tvClassTwo.setOnClickListener(myClickListener);
		llHolder.setOnClickListener(myClickListener);

		etGoodsName.addTextChangedListener(myTextWatcher);
		etGoodsNumber.addTextChangedListener(myTextWatcher);
		etGoodsPrice.addTextChangedListener(myTextWatcher);
		// etGoodsDescribe.addTextChangedListener(myTextWatcher);
		tvClassOne.addTextChangedListener(myTextWatcher);
		tvClassTwo.addTextChangedListener(myTextWatcher);

		if (TO_ADD_GOODS) {
			tvTitle.setText("添加新产品");
			showNewPicture();
			// supPriceControl.addPriceItem("", "", "");
		} else {
			tvTitle.setText("修改商品");
			showRevampData();
			// supPriceControl.allOtherInput = true;
		}

	}

	/**
	 * 将新拍照的相片提取显示出来
	 */
	private void showNewPicture() {
		if (SupCache.pictureList != null) {
			for (int i = 0; i < SupCache.pictureList.size(); i++) {
				mySquarePicture.show(SupCache.pictureList.get(i));
			}
		}
	}

	/**
	 * 加载显示要修改的资料
	 */
	private void showRevampData() {
		myCloth = SupCache.cloth;
		etGoodsName.setText(myCloth.getClothName());
		etGoodsNumber.setText(String.valueOf(myCloth.getClothId()));
		tvClassOne.setText(myCloth.getClothGeneralType());
		tvClassTwo.setText(myCloth.getClothDetailsType());
		// etGoodsDescribe.setText(myCloth.getClothDescribe());

		if (myCloth.getPrices() != null && myCloth.getPrices().size() > 0) {
			etGoodsPrice.setText(myCloth.getPrices().get(0).getPrice() + "");
			// for (int i = 0; i < myCloth.getPrices().size(); i++) {
			// Price price = myCloth.getPrices().get(i);
			// supPriceControl.addPriceItem(price.getWantNumberFrom(),
			// price.getWantNumberTo(),
			// String.valueOf(price.getPrice()));
			// }
		}

		if (SupCache.pictureList != null
				&& EnvironmentUtil.checkNetState(getBaseContext())) {
			for (int i = 0; i < SupCache.pictureList.size(); i++) {
				mySquarePicture.show(SupCache.pictureList.get(i));
			}
		}

	}

	/**
	 * 获取所有输入框的文本列表
	 * 
	 * @return
	 */
	private List<String> getInputList() {
		List<String> strList = new ArrayList<String>();

		strList.add(etGoodsName.getText().toString());
		strList.add(etGoodsNumber.getText().toString());
		strList.add(tvClassOne.getText().toString());
		strList.add(tvClassTwo.getText().toString());
		strList.add(etGoodsPrice.getText().toString());
		// strList.add(etGoodsDescribe.getText().toString());

		return strList;
	}

	/**
	 * 判断要提交填写的资料格式是否正确
	 * 
	 * @return
	 */
	private boolean checkCommitData() {
		List<String> strList = getInputList();

		if (strList.get(0).length() >= 48) {
			etGoodsName.requestFocus();
			ToastUtil.show(this, "物品名称不能超过48个字符");
			return false;
		}
		if (strList.get(1).length() >= 36) {
			etGoodsNumber.requestFocus();
			ToastUtil.show(this, "商品编号不能超过36个字符");
			return false;
		}
		if (strList.get(2).equals("") || strList.get(2) == null) {
			tvClassOne.requestFocus();
			ToastUtil.show(this, "请选择类别");
			return false;
		}
		if (strList.get(3).equals("") || strList.get(3) == null) {
			tvClassTwo.requestFocus();
			ToastUtil.show(this, "请选择类别");
			return false;
		}
		// if (strList.get(4).length() >= 400) {
		// etGoodsDescribe.requestFocus();
		// ToastUtil.show(this, "商品描述不能超过200个字");
		// return false;
		// }

		// if (!supPriceControl.checkPriceInput(true)) {
		// return false;
		// }

		return true;
	}

	/**
	 * 判断是否有图片输入 状态3是已经上传但中断又被删时给的状态
	 * 
	 * @param pictures
	 * @return
	 */
	private boolean checkInputPicture(List<Picture> pictures) {
		if (pictures != null) {
			for (int i = 0; i < pictures.size(); i++) {
				if (3 != pictures.get(i).getPictureState()) {
					return true;
				}
			}
		}
		return false;

	}

	/**
	 * 判断所有输入框是否都有输入
	 * 
	 * @return
	 */
	private void checkAllInput() {
		List<String> strList = getInputList();
		ivCommitButton.setEnabled(false);
		// supPriceControl.allOtherInput = false;

		for (int i = 0; i < strList.size(); i++) {
			if (strList.get(i).equals("") || strList.get(i) == null) {
				return;
			}
		}
		if (!checkInputPicture(SupCache.pictureList)) {
			return;
		}
		// if (llGoodsPrice.getChildCount() <= 0) {
		// return;
		// }

		// supPriceControl.allOtherInput = true;

		// if (!supPriceControl.checkPriceInput(true)) {
		// return;
		// }
		ivCommitButton.setEnabled(true);
	}

	/**
	 * 数据提交结果的处理
	 */
	private void commitResult() {

		try {
			if (CheckStateUtil.check(goodsGsonBean)) {
				ToastUtil.show(getBaseContext(), "资料提交成功!");
				Intent intent = null;
				if (TO_ADD_GOODS) {
					intent = new Intent(getBaseContext(),
							SupGoodsManagerActivity.class);
				} else {
					myCloth = DataUtil.gson.fromJson(
							goodsGsonBean.getStrJson(), Cloth.class);
					SupCache.cloth = myCloth;
					intent = new Intent(getBaseContext(),
							SupGoodsDetailsActivity.class);
				}
				SupCache.pictureList.clear();
				startActivity(intent);
				this.finish();
			}

		} catch (Exception e) {
			e.printStackTrace();
			ToastUtil.show(getBaseContext(), "资料提交失败，请重新提交！");
		}

	}

	/**
	 * 
	 * 选择获取图片的方式的回调
	 */
	class TakePhotoForPicture implements MyCallBack {
		@Override
		public void callback(String choose) {
			if (choose.equals("拍照")) {
				if (!SupCache.initialCamera) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							MyStateUtil.SYSTEM_CAMERA_RETURN);
				} else {
					Intent intent = new Intent(getBaseContext(),
							SupCameraActivity.class);
					startActivityForResult(intent, MyStateUtil.CAMERA_TO_ADD);
				}
			} else {
				try {
					Intent intent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent,
							MyStateUtil.SYSTEM_FOLDER_RETURN);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 确定退出物品添加
	 */
	class sureExit implements MyCallBack {
		@Override
		public void callback(String choose) {
			Intent intent = null;
			switch (SupCache.from) {
			case 2:
				intent = new Intent(getBaseContext(),
						SupGoodsDetailsActivity.class);
				break;
			case 1:
				intent = new Intent(getBaseContext(),
						SupGoodsManagerActivity.class);
				break;
			default:
				intent = new Intent(getBaseContext(), SupIndexActivity2.class);
				break;
			}
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			SupInputGoodsInfoActivity.this.finish();
		}
	}

	/**
	 * 文本监听的回调
	 */
	class textWhatcherBack implements MyCallBack {

		@Override
		public void callback(String choose) {
			checkAllInput();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			Bitmap bitmap = null;
			String path = null;
			Picture picture = new Picture();
			picture.setPictureState(DataState.INITIAL);
			switch (requestCode) {
			case MyStateUtil.SYSTEM_CAMERA_RETURN:
				bitmap = data.getParcelableExtra("data");
				path = imageManager.saveBitmap(bitmap);
				mySquarePicture.getImageView(path, false);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.CLOTH_TYPE);
				if(SupCache.pictureList == null){
					SupCache.pictureList = new ArrayList<Picture>();
				}
				SupCache.pictureList.add(picture);
				SupCache.isChangePicture = true;
				break;

			case MyStateUtil.SYSTEM_FOLDER_RETURN:
				path = ImageUtil.getAbsoluteImagePath(data.getData(), this);
				mySquarePicture.getImageView(path, false);
				picture.setPictureUrl(path);
				picture.setPictureType(MyReturnState.CLOTH_TYPE);
				if(SupCache.pictureList == null){
					SupCache.pictureList = new ArrayList<Picture>();
				}
				SupCache.pictureList.add(picture);
				SupCache.isChangePicture = true;
				break;

			case MyStateUtil.CAMERA_TO_ADD:
			case MyStateUtil.GALLERY_RETURN:
				llGoodsPicture.removeAllViews();
				// llGoodsPrice.removeAllViews();
				if (TO_ADD_GOODS) {
					// supPriceControl.addPriceItem("", "", "");
					showNewPicture();
				} else {
					showRevampData();
				}
			default:
				break;
			}
			bitmap = null;
			if (SupCache.isChangePicture) {
				checkAllInput();
			}
			SupCache.isChangePicture = false;
			picture = null;
		}

	}

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			myAlertDialog.show("您确定退出物品信息填写吗？", new sureExit());
			return false;
		}
		return false;
	}

	/**
	 * 设置各控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			EnvironmentUtil.closeInputMethod(SupInputGoodsInfoActivity.this);

			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				myAlertDialog.show("您确定退出物品信息填写吗？", new sureExit());
				break;

			case R.id.ivAddNewGoodsPictureButton:
				myListDialog.show("请选择", new String[] { "拍照", "本地文件" },
						new TakePhotoForPicture());
				break;

			// case R.id.ivAddNewGoodsPriceButton:
			// supPriceControl.addPriceItem("", "", "");
			// break;

			case R.id.ivPublicTitleOther:
				if (checkCommitData()) {
					normalDataLoader.load();
				}
				break;

			case R.id.tvAddNewGoodsClassifyOne:
				showClassifyDialog.showClassOne();
				break;

			case R.id.tvAddNewGoodsClassifyTwo:
				showClassifyDialog.showClassTwo();
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myProgressDialog.show("提示", "提交中，请稍候...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		try {
			for (int i = 0; i < SupCache.pictureList.size(); i++) {
				if (SupCache.pictureList.get(i).getPictureState() == DataState.INITIAL
						||SupCache.pictureList.get(i).getPictureState() == DataState.CAMERE_INITIAL) {
					SupCache.pictureList.get(i).setPictureState(DataState.INITIAL);
					GsonBean gsonBean = fileUploadService
							.upLoadPicture(SupCache.pictureList.get(i)
									.getPictureUrl());
					if (CheckStateUtil.check(gsonBean)) {
						Picture pictureReturn = DataUtil.gson.fromJson(
								gsonBean.getStrJson(), Picture.class);
						SupCache.pictureList.set(i, pictureReturn);
					}
				}
			}

			List<String> strList = getInputList();
			Price price = new Price();
			price.setPrice(Double.valueOf(strList.get(4)));
			price.setWantNumberFrom("0");
			price.setWantNumberTo("0");
			List<Price> prices = new ArrayList<Price>();
			prices.add(price);

			Cloth cloth = new Cloth();
			cloth.setSupId(keyCache.supId);
			cloth.setClothId(myCloth.getClothId());
			cloth.setClothName(strList.get(0));
			cloth.setClothItemNumber(strList.get(1));
			cloth.setClothGeneralType(strList.get(2));
			cloth.setClothDetailsType(strList.get(3));
			cloth.setPrices(prices);

			cloth.setClothDescribe("无");
			// cloth.setPrices(supPriceControl.getPriceList());
			cloth.setPictures(SupCache.pictureList);

			if (EnvironmentUtil.checkNetState(getBaseContext())) {
				myCloth = cloth;

				System.out.println("commit the data");

				if (TO_ADD_GOODS) {
					System.out.println("add the info");
					goodsGsonBean = addGoodsService.execute(cloth);
				} else {
					System.out.println("revamp the info");
					goodsGsonBean = revampGoodsService.execute(cloth);
				}
				msg.what = MyStateUtil.UPLOAD_RESULT;
			} else {
				msg.what = MyStateUtil.NOT_NET_CONNECTION;
			}
		} catch (Exception e) {
			e.printStackTrace();
			SupCache.pictureList.clear();
			msg.what = MyStateUtil.UPLOAD_ERROR;
		} 
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myProgressDialog.cancle();
		switch (state) {
		case MyStateUtil.UPLOAD_RESULT:
			commitResult();
			break;
		case MyStateUtil.UPLOAD_ERROR:
			ToastUtil.show(getBaseContext(), "上传出错，请重新提交");
			break;
		case MyStateUtil.GET_CLASSONE_RETURN:
			showClassifyDialog.showClassOne();
			break;
		case MyStateUtil.GET_CLASSTWO_RETURN:
			showClassifyDialog.showClassTwo();
			break;
		case MyStateUtil.RETURN_FAIL:
			ToastUtil.show(getBaseContext(), "无对应数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "无网络连接");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			break;
		}
	}

}
